#include "MsgRequester.h"
#include "CmdId.h"
#include "proto_package.h"
#include "proto_msg_handler.h"
#include <gflags/gflags.h>
DEFINE_uint64(sessionid, E_MODULE_ID_FILE_UPLOAD_CHECK, "会话id");
DEFINE_uint64(destmoduleid, E_MODULE_ID_FILE_UPLOAD_CHECK, "目的地模块id");
CMsgRequester::CMsgRequester(uv_loop_t* loop) :m_timer(loop)
{
	m_clientPtr = CTCPClient::NewTCPClien(loop);
	m_devPtr = CTCPClient::NewTCPClien(loop);
	CMsgReqHandler* hlr = new CMsgReqHandler;	
	m_msgHlrPtr = CMsgHandlerPtr(hlr);			
	m_devMsgHlrPtr = CMsgHandlerPtr(new CMsgReqHandler);
}


CMsgRequester::~CMsgRequester()
{
	LOG_INFO("~CWebDevMsgRequster()");	
}

void CMsgRequester::SetModuleID(uint32_t moduleid)
{
	m_moduleID = moduleid;
	((CMsgReqHandler*)(m_msgHlrPtr.get()))->m_moduleID = moduleid;
}

void CMsgRequester::SetDestMoudleID(uint32_t moduleid)
{	
	m_destModuleID = moduleid;
	((CMsgReqHandler*)(m_msgHlrPtr.get()))->m_destModuleID = moduleid;
}


void CMsgRequester::StopSvr()
{	
	m_clientPtr->CloseConn();
	m_devPtr->CloseConn();
}

void CMsgRequester::StartSendDevMsg(std::string ip, uint16_t port)
{	
	m_clientPtr->OnConnStatus([=](CTCPClientPtr clt, int status){
		if (status == 0)
		{

			SBuf msg;		
			CProtoPackage::PackStopVedioUploadReq(m_destModuleID, m_moduleID, &msg);			
			clt->Write(msg.data(), msg.len());

			clt->OnMsgCall([=](SessionPtr session, char* szByte, int len){
				m_msgHlrPtr->HandleMsg(session, szByte, len);
			});

			clt->OnClose([=](SessionPtr session) {
				printf("client close\n");				
			});

		}		
	});
	m_clientPtr->SetReConnInteral(5 * 1000);
	m_clientPtr->Connect((char*)ip.c_str(), port);
}

void CMsgRequester::StartSendFileCheckMsg(std::string ip, uint16_t port)
{
	m_devPtr->OnConnStatus([=](CTCPClientPtr clt, int status){
		if (status == 0)
		{
			SBuf msg;			
			CProtoPackage::PackFileCheckReq(m_destModuleID, &msg);
			clt->Write(msg.data(), msg.len());
			clt->OnMsgCall([=](SessionPtr session, char* szByte, int len){
				m_devMsgHlrPtr->HandleMsg(session, szByte, len);
			});
			clt->OnClose([=](SessionPtr session) {
				printf("client close\n");				
			});
		}
	});
	m_devPtr->SetReConnInteral(5 * 1000);
	m_devPtr->Connect((char*)ip.c_str(), port);
}